 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.dto.in.UserDto;
import com.zdkj.subway.rca.entity.SwCkOthenYjzpManagementLog;
import com.zdkj.subway.rca.entity.SwCkOthenYjzpManagementTmp;
import com.zdkj.subway.rca.mapper.SwCkOthenYjzpManagementTmpMapper;
import com.zdkj.subway.rca.service.SwCkOthenYjzpManagementLogService;
import com.zdkj.subway.rca.service.SwCkOthenYjzpManagementService;
import com.zdkj.subway.rca.service.SwCkOthenYjzpManagementTmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 其他运营商应急纸票导入临时表
 *
 * @author stw
 * @date 2020-12-31 19:31:38
 */
@Service
public class SwCkOthenYjzpManagementTmpServiceImpl extends ServiceImpl<SwCkOthenYjzpManagementTmpMapper, SwCkOthenYjzpManagementTmp> implements SwCkOthenYjzpManagementTmpService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkOthenYjzpManagementTmpServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd HH:mm:ss";
    @Autowired
    private SwCkOthenYjzpManagementService swCkOthenYjzpManagementService;

    @Autowired
    private SwCkOthenYjzpManagementLogService swCkOthenYjzpManagementLogService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
		ExcelReaderBuilder excelReaderBuilder = EasyExcel.read(excelFile);
    	List<ReadSheet> sheets = excelReaderBuilder.build().excelExecutor().sheetList();

        List<Map<String,String>> lineMap = this.baseMapper.selectLineMap();
        //List<Map<String,String>> stationMap = this.baseMapper.selectStationMap();暂时不需要再查车站名称

        List<Map<String,String>> projectItemMap = swCkOthenYjzpManagementService.selectProjectItemMap();
		List<SwCkOthenYjzpManagementTmp> listDb = new ArrayList<>();
		//String lineCode = "54";
		//String lineName = "14号线机场段";
        for(int n = 0; n < 2; n++) {//只有两个sheet
		  String projectItem = "发售";//发售1
		  if(n==0){
		     projectItem ="回收";//2
		  }		 
		  List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet(n).headRowNumber(1).doReadSync();
		  if (CollectionUtil.isNotEmpty(listMap)) {
              Map<Integer, String> integerStringMap = listMap.get(0);
              String lineCode = getLineCode(lineMap,integerStringMap.get(1));
              String lineName = integerStringMap.get(1);

              String reportTypeTmp = integerStringMap.get(4);//应急纸票类型 1和2
              Map<String,String> reportTypeMap = swCkOthenYjzpManagementService.selectReportTypeMap(reportTypeTmp);

              for (int m = 2; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
				if(StringUtils.isEmpty(data.get(2))){//日期为空不加入                	
                	break;
                }

                SwCkOthenYjzpManagementTmp tmpObj = new SwCkOthenYjzpManagementTmp();
				tmpObj.setLineCodeTmp(lineName);
				tmpObj.setLineCode(lineCode);
				tmpObj.setReportType(reportTypeMap.get("value"));
				tmpObj.setReportTypeTmp(reportTypeTmp);
				tmpObj.setProjectItemTmp(projectItem);
				if(n==0){
				   tmpObj.setProjectItem("2");
				}else{
				   tmpObj.setProjectItem("1");
				}
                tmpObj.setStationCodeTmp(data.get(1));//车站名称
				tmpObj.setStationCode(data.get(1));//车站名称，不需要转换
                tmpObj.setStatisticsDateTmp(data.get(2));//日期 
				tmpObj.setItemUnitTmp(data.get(3));                
				tmpObj.setItemAmountTmp(data.get(4));              
                tmpObj.setItemMoneyTmp(data.get(5));

                if (StringUtils.isEmpty(tmpObj.getStatisticsDateTmp())) {
                    break;
                }
                if (!parseDate(tmpObj.getStatisticsDateTmp())) {
                    continue;
                }
                final SwCkOthenYjzpManagementTmp obj = ObjectUtils.getDefaultObj(SwCkOthenYjzpManagementTmp.class);
                BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                checkErr(obj,null,projectItemMap);
                listDb.add(obj);

               }		  
		   }
		 
		}//sheet结束
		MultipartFileToFile.delteTempFile(excelFile);
		if(!listDb.isEmpty()) {
		    Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listDb);
		}
       return false;
    }

    private String getLineCode (List<Map<String,String>> lineMap,String lineName) {
        for (Map<String,String> map : lineMap){
            if(lineName.equals(map.get("NAME"))){
                return map.get("CODE");
            }
        }
        return "";
    }

    private String getStationCode (List<Map<String,String>> stationMap,String stationName,String lineCode) {
        for (Map<String,String> map : stationMap){
            if(stationName.equals(map.get("NAME")) && lineCode.equals(map.get("LINE_CODE"))){
                return map.get("CODE");
            }
        }
        return "";
    }
    private String getProjectItemCode (List<Map<String,String>> projectItemMap,String projectItemName) {
        for (Map<String,String> map : projectItemMap){
            if(projectItemName.equals(map.get("label"))){
                return map.get("value");
            }
        }
        return "";
    }
    private void checkErr(SwCkOthenYjzpManagementTmp obj,List<Map<String,String>> stationMap,List<Map<String,String>> projectItemMap) {
        //更新字段
        try {
            String statisticsDateTmp = obj.getStatisticsDateTmp();
            Date statisticsDate = DateUtils.parseDate(statisticsDateTmp, parsePattern);
            obj.setStatisticsDate(statisticsDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        } catch (Exception e) {
            obj.setErrMsg("收票日期 为空或格式错误");
        }
        /*
        if(StringUtils.isNotEmpty(obj.getLineCodeTmp())){
            String lineCode = getLineCode(lineMap,obj.getLineCodeTmp());
            if(StringUtils.isNotEmpty(lineCode)){
                obj.setLineCode(lineCode);
            } else {
                obj.setErrMsg("线路名称 为空或不规范");
            }

        } else {
            obj.setErrMsg("线路名称 为空");
        }

        if(StringUtils.isNotEmpty(obj.getStationCodeTmp()) && StringUtils.isNotEmpty(obj.getLineCode())){
            String stationCode = getStationCode(stationMap,obj.getStationCodeTmp(),obj.getLineCode());
            if(StringUtils.isNotEmpty(stationCode)){
                obj.setStationCode(stationCode);
            } else {
                obj.setErrMsg("车站名称 为空或不规范");
            }
        } else {
            obj.setErrMsg("车站名称 为空");
        }*/
		/*
        if(StringUtils.isNotEmpty(obj.getProjectItemTmp())){
            String projectItem = getProjectItemCode(projectItemMap,obj.getProjectItemTmp());
            if(StringUtils.isNotEmpty(projectItem)){
                obj.setProjectItem(projectItem);
            } else {
                obj.setErrMsg("项目名称 为空或不规范");
            }
        } else {
            obj.setErrMsg("项目名称 为空");
        }*/

        try {
            String itemAmountTmp = obj.getItemAmountTmp();
            //Integer itemAmount = Integer.parseInt(itemAmountTmp);
            Integer itemAmount = Double.valueOf(itemAmountTmp).intValue();
            obj.setItemAmount(itemAmount);
        } catch (Exception e) {
            obj.setErrMsg("张数 为空或格式错误");
        }
       try {
            BigDecimal numUnit = new BigDecimal("100");

            String itemUnitTmp = obj.getItemUnitTmp();
            BigDecimal itemUnit = new BigDecimal(itemUnitTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            itemUnit = itemUnit.multiply(numUnit);
            obj.setItemUnit(itemUnit.longValue());

        } catch (Exception e) {
            obj.setErrMsg("票面金额 为空或格式错误");
        }
        try {
            BigDecimal num = new BigDecimal("100");

            String itemMoneyTmp = obj.getItemMoneyTmp();
            BigDecimal itemMoney = new BigDecimal(itemMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            itemMoney = itemMoney.multiply(num);
            obj.setItemMoney(itemMoney.longValue());

        } catch (Exception e) {
            obj.setErrMsg("合计金额 为空或格式错误");
        }


        //判断数据是否存在
		/*
        SwCkOthenYjzpManagement swCkOthenYjzpManagement = new SwCkOthenYjzpManagement();
        BeanUtils.copyProperties(obj, swCkOthenYjzpManagement, "deptId","creatorId","creatorName","createTime");
        int cont = swCkOthenYjzpManagementService.count(Wrappers.query(swCkOthenYjzpManagement));
        if (cont > 0) {
            obj.setErrMsg("数据已存在");
        }*/
    }



    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(UserDto user) {
        List<Map<String,String>> mapList = this.baseMapper.selectMaxMinStatisticsDate(user.getId());
        if(CollectionUtil.isEmpty(mapList)) {
            return;
        }
        String uuid = UUID.randomUUID().toString().toLowerCase();
        Map<String, String> map1 = mapList.get(0);
        String lineCode = map1.get("lineCode");
        String reportType = map1.get("reportType");

        for (Map<String, String> map : mapList) {
            String minStatisticsDate = map.get("minStatisticsDate");
            String maxStatisticsDate = map.get("maxStatisticsDate");
            String projectItem = map.get("projectItem");

            SwCkOthenYjzpManagementLog swCkOthenYjzpManagementLog = new SwCkOthenYjzpManagementLog();
            swCkOthenYjzpManagementLog.setBeginTime(LocalDate.parse(minStatisticsDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            swCkOthenYjzpManagementLog.setEndTime(LocalDate.parse(maxStatisticsDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            swCkOthenYjzpManagementLog.setSubmitPersonId(user.getId());
            swCkOthenYjzpManagementLog.setSubmitPersonCode(user.getUserCode());
            swCkOthenYjzpManagementLog.setSubmitPersonName(user.getNikeName());
            swCkOthenYjzpManagementLog.setCreatorId(user.getId());
            swCkOthenYjzpManagementLog.setDeptId(user.getDeptId());
            swCkOthenYjzpManagementLog.setCreatorName(user.getNikeName());
            swCkOthenYjzpManagementLog.setUuid(uuid);
            swCkOthenYjzpManagementLog.setLineCode(lineCode);//线路
            swCkOthenYjzpManagementLog.setReportType(reportType);//应急纸票类型
            swCkOthenYjzpManagementLog.setProjectItem(projectItem);//应急纸票子类型

            swCkOthenYjzpManagementLogService.save(swCkOthenYjzpManagementLog);
        }
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(user.getId(),lineCode,reportType);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(user.getId(),uuid);
        //this.baseMapper.saveBatchWithExcelOk(user.getId(),uuid);
        saveBatchWithExcelCancel(user.getId());
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }

}
